#!/usr/bin/bash

if [[ -z "$1" ]]; then
    echo usage: ${0##*/} URL 1>&2
    exit -1
fi

url=$1

now=$(date +%s)
lastvisit=$((now - 60 * 10))
lastactivity=$((now - 60 * 5))
echo Now: $now
echo Last visit: $lastvisit
echo Last activity: $lastactivity

header_file=header.$$.txt
output_file=curl.$$.out
referer=https://dream4ever.org/index.php?s=

# grab the file
# WARNING: YOU MUST CHANGE THE `drluserid' and `drlpassword' FIELDS ACCORDINGLY
curl --dump-header $header_file --output $output_file --referer $referer --insecure \
    --cookie "drllastvisit=$lastvisit;drllastactivity=$lastactivity;drluserid=XXXX;drlpassword=XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" \
    --url $url

# rename
if filename=$(iconv -f UTF-8 -t GBK $header_file | grep -ihoP '(?<=; filename=").*(?=")'); then
    if [[ -f $filename ]]; then
        echo "ERROR: $filename: exists!" 1>&2
        echo "  The downloaded file remains as: $output_file" 1>&2
    else
        mv -f $output_file $filename
        echo "Download success: $filename" 1>&2
    fi
else
    echo "ERROR: file name not found!" 1>&2
fi

rm -f $header_file
